import re
from flask import Blueprint
from flask import request,jsonify,send_from_directory
from db import Db
import redis
from mypage import Page
from myfile import MyFile
import os
import math


good= Blueprint('good',__name__)

@good.route('/addgoods/',methods=['POST'])
def addgoods():
    name = request.form.get('name')
    price = request.form.get('price')
    db = Db()
    res = db.get_one("select `id` from `goods` where name='%s'"%name)
    if res:
        return {'code':10010,'msg':'商品已存在'}
    else:
        db.insert("insert into `goods` (name,price) values ('%s','%s')"%(name,price))
        res = db.get_one("select `id` from `goods` where name = '%s'"%name)
        myfile = MyFile()
        myfile.mkdir(res['id'])
        return {'code':200,'goodid':res['id']}

@good.route('/addgoodsimg/',methods=['POST'])
def addgoodsimg():
    f = request.files['file']
    id = request.form.get('id')
    f.save(os.path.join('./static/upload/'+str(id),f.filename))
    try:
        db = Db()
        db.update("update `goods` set `img`='%s' where id=%s"%(f.filename,id))
    except Exception as e:
        return {'code':400,'msg':'上传失败'}
    else:
       return {'code':200,'filename':f.filename} 

@good.route('/getgoods/',methods=['GET'])
def getgoods():
    #当前页
    page = int(request.args.get('page',1))
    db = Db()
    count = db.get_one("select count(1) as total from `goods`")
    mypage = Page(count['total'],page,2)
    page_num =mypage.page_num()
    sql = "select * from `goods`"
    res = mypage.get_data(sql)
    return {'code':200,'page_num':page_num,'data':res}

@good.route('/dulogin/',methods=['POST'])
def dulogin():
    username = request.form.get('username')
    password = request.form.get('password')
    db = Db()
    res = db.get_one("select * from `duser` where username= '%s'"%username)
    if res:
        if res['password'] == password:
            return {'code':200,'msg':'登陆成功','uid':res['id']}
        else:
           return {'code':400,'msg':'密码错误'} 
    else:
        return {'code':10010,'msg':'该用户不存在'}

@good.route('/user_depar/',methods=['GET'])
def user_depar():
    page = int(request.args.get('page'))
    keyword = request.args.get('keyword','')
    keyword = keyword.strip("")
    db = Db()
    sql = "select count(1) as total from `duser`"
    if keyword:
        sql2 = " where username like '%%%s%%'"%keyword
        sql+=sql2
        print(sql)
        count = db.get_one(sql)
        count = count['total']
        sql = "select department.id,department.name,duser.username,case duser.authority when 1 then '超级用户' when 2 then '普通用户' end as authority   from `department` left join `duser` on department.id=duser.did"
        sql+=" where duser.username like '%%%s%%'"%keyword
        page = Page(count,page,3)
        page_num = page.page_num()
        res = page.get_data(sql)
        return {'code':200,'data':res,'page_num':page_num}
    else:
        count =db.get_one(sql)
        count = count['total']
        sql = "select department.id,department.name,duser.username,case duser.authority when 1 then '超级用户' when 2 then '普通用户' end as authority   from `department` left join `duser` on department.id=duser.did"
        page = Page(count,page,3)
        page_num = page.page_num()
        res = page.get_data(sql)
        return {'code':200,'data':res,'page_num':page_num}


@good.route('/adddepar/',methods=['POST'])
def adddepar():
    name = request.form.get('name')
    id = request.form.get('id')
    db = Db()
    res = (db.get_one("select `authority` from `duser` where id=%s"%id))['authority']
    if res == 2:
        return {'code':400,'msg':'你没有权限,只能搜索查找'}
    
    else:
        res = db.get_one("select `id` from `department` where name='%s'"%name)
        if res:
            return {'code':10010,'msg':'部门已存在'}
        else:
            db.insert("insert into `department` name values '%s'")%name
            return {'code':200}

@good.route('/adduser/',methods=['POST'])
def addduser():
    username = request.form.get('username')
    password = request.form.get('password')
    authority = int(request.form.get('authority'))
    did = request.form.get('did')
    id = request.form.get('id')
    db = Db()
    res = (db.get_one("select `authority` from `duser` where id=%s"%id))['authority']
    if res == 2:
        return {'code':400,'msg':'你没有权限,只能搜索查找'}
    else:
        res = db.get_one("select `id` from `duser` where username='%s'"%username)
        if res:
            return {'code':10010,'msg':'部门已存在'}
        else:
            db.insert("insert into `duser` (username,password,authority,did) values ('%s','%s','%s','%s')")%(username,password,authority,did)
            return {'code':200}

@good.route('/getdepars/',methods=['GET'])
def getdepars():
    db = Db()
    res = db.get_all("select * from `department`")
    return jsonify(res)




    

    




